package org.persistente.xml;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author philipe
 */
public class CompositeParser<T> extends Parser<T> {
    
    private Map<String, Parser> parsers;
    private Class<T> cl;

    public CompositeParser(Map<String, Parser> parsers, Class<T> cl) {
        this.parsers = parsers;
        this.cl = cl;
    }

    public CompositeParser(Class<T> cl) {
        this.cl = cl;
        this.parsers = new HashMap<String, Parser>();
    }
    
    public void add(String name, Parser parser){
        parsers.put(name, parser);
    }
    
    public Object newObject(){
        try {
            return cl.newInstance();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } 
    }
    
    public Class<T> getCompositeClass(){
        return cl;
    }
    

    @Override
    public void init(Context context) {
        context.objects.push(newObject());
    }

    @Override
    public void start(Context context, String attribute) {
        Parser parser = parsers.get(attribute);
        if(parser == null){
            parser = new NullParser();
        }
        context.attributes.push(attribute);
        context.parsers.push(parser);
        parser.init(context);
    }
    
    private String toCamelCase(String s){
        String c = CamelCase.toCamelCase(s, "-");
        return Character.toLowerCase(c.charAt(0)) + c.substring(1);
    }
    

    @Override
    public void use(Context context, String attribute, Object value) {
        Object obj = context.objects.peek();
        try {
            attribute = toCamelCase(attribute);
            cl.getField(attribute).set(obj, value);
        } catch (NoSuchFieldException ex) {
            //ignora atributos do xml desconhecidos            
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }         
    }
    
    
}
